"use client";
import { useEffect, useRef, useState } from 'react';
import { StatusBar } from './components/StatusBar';
import { LogPanel } from './components/LogPanel';
import { ControlPanel } from './components/ControlPanel';
import { MapService } from './service/MapService';
import 'leaflet/dist/leaflet.css';


export type WsStatus = 'connected' | 'disconnected' | 'error';

export interface LogEntry {
  message: any;
  type: 'client' | 'server';
  timestamp: string;
}

const Map = () => {
  const [wsStatus, setWsStatus] = useState<WsStatus>('disconnected');
  const [logs, setLogs] = useState<LogEntry[]>([]);
  const mapRef = useRef<HTMLDivElement>(null);
  const mapService = useRef<MapService | null>(null);

  const addLog = (message: any, type: 'client' | 'server') => {
    setLogs(prev => [...prev.slice(-99), {
      message: typeof message === 'object' ? message : JSON.parse(message),
      type,
      timestamp: new Date().toISOString()
    }]);
  };

  useEffect(() => {
    if (!mapRef.current) return;
    
    mapService.current = new MapService(mapRef.current, setWsStatus, addLog);
    mapService.current.init();  // 初始化WebSocket等逻辑
    // 挂载 DrawInteraction 到 window，供 SelectInteraction 多边形选中使用
    if (!(window as any).DrawInteraction) {
      import('./drawing/DrawInteraction').then(mod => {
        (window as any).DrawInteraction = mod.DrawInteraction;
      });
    }

    return () => {
      mapService.current?.destroy();
    };
  }, []);

  return (
    <div style={{ 
      display: 'grid',
      gridTemplateColumns: '50% 50%',
      gridTemplateRows: '50% 50%',
      height: '100vh', 
      padding: 20, 
      gap: 20,
      fontFamily: 'Arial, sans-serif',
      backgroundColor: '#f5f5f5'
    }}>
      <div style={{ 
        gridColumn: '1',
        gridRow: '1',
        display: 'flex',
        flexDirection: 'column',
        gap: 20 
      }}>
        <h1 style={{ margin: 0, color: '#333' }}>Leaflet 地图示例</h1>
        <div ref={mapRef} style={{ 
          flex: 1,
          borderRadius: 8,
          boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
          backgroundColor: 'white',
          position: 'relative',
          overflow: 'hidden'
        }}>
          {/* 控制面板按钮置顶且美化，背景透明不遮挡地图 */}
          <div style={{
            position: 'absolute',
            top: 0,
            left: 50,
            zIndex: 1000,
            display: 'flex',
            pointerEvents: 'auto', // 阻挡地图交互
          }}>
            
            <ControlPanel mapService={mapService} />
            
          </div>
        </div>
      </div>

      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 20 }}>
        <StatusBar wsStatus={wsStatus} />
        <LogPanel logs={logs} />
      </div>
    </div>
  );
};


export default Map;
